package com.orangelife.mobile.shop.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.common.sp.UserSp;
import com.curry.android.http.HttpUtil;
import com.curry.android.net.NetworkUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.ImageDownloader;
import com.curry.android.util.ImageDownloader.ImageSize;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.PhoneCallUtil;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.common.jump.CommonJumper;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.discount.activity.DetailActivity;
import com.orangelife.mobile.point.activity.MyPointActivity;
import com.thirdsdk.umeng.UmShareBiz;
import com.orangelife.mobile.util.BLog;
import com.orangelife.mobile.util.FileHelper;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.TimeUtil;
import com.orangelife.mobile.util.ToastHelper;
import com.orangelife.mobile.widget.SelectPicPopupWindowView;
import com.orangelife.mobile.web.WebWin;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.sso.UMSsoHandler;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;

/**
 * 商家详情
 *
 * @author lxj
 */
public class TraderDetailActivity extends OrangeLifeBaseActivity {
    /** 弹出框 */
    SelectPicPopupWindowView menuWindow;
    /** 商家详情标题、标题栏的积分、商家标题、商家地址、商家简介、商家详细介绍 */
    private TextView tvTraderDetailTitle, tvTitleScore, tvTraderTitle,
            tvTraderAddress, tvTraderIntroDetail, tvOne;
    /** 商家图片、商家类型 、分享、优惠 */
    private ImageView ivTraderPic, ivTraderType, ivTraderShare, ivPreferential;
    /** 商家照片 */
    private WebWin wwPhoto;
    /** 打电话按钮 */
    private ImageView ivCall;
    /** 地图 */
    private LinearLayout llMap;
    private Map<String, Object> map = null;
    private Map<String, Object> mapDetail;
    /** 积分的点击 */
    private LinearLayout llScore;
    /** 进度条 */
    private Dialog dialog = null;
    /** 判断是热门商家还是商家 */
    private String str = null;
    /** 照片填空器 */
    private ImageDownloader image = null;
    /** 经度 */
    private float longitude;
    /** 纬度 */
    private float latitude;
    /** 用来储存通话记录的文件 */
    private String filename;

    /** -------------分享------------------------ */
    /** 分享title */
    private String uMtitle = "";
    /** 分享content */
    private String uMcontent = "";
    private String merId;
    private boolean hadCall = false;
    /**
     * 首先在您的Activity中添加如下成员变量
     */
    private final UMSocialService mController = UMServiceFactory
            .getUMSocialService("com.umeng.share");
    UmShareBiz shareBiz;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trader_detail);
        shareBiz = new UmShareBiz(this);
        initView();
        findView();
    }

    String memID = null;

    @Override
    protected void onStart() {
        super.onStart();
        if (str != null) {
            memID = map.get("merID").toString();
        } else {
            if (map == null) {
                Intent intent = getIntent();
                memID = intent.getStringExtra("merID");
            } else {
                memID = map.get("merID").toString();
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (map != null) {
            if (map.containsKey("state") && map.get("state").toString().equals("1")) {
                BLog.getInstance().outMerDetail(map.get("merID") + "");
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        JPushInterface.onResume(this);
        if (map != null) {
            if (map.containsKey("state") && map.get("state").toString().equals("1")) {
                BLog.getInstance().inMerDetail(map.get("merID") + "");
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(
                resultCode);
        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

    /**
     * 初始化
     */
    private void initView() {
        tvTraderDetailTitle = (TextView) findViewById(R.id.tv_title);
        tvOne = (TextView) findViewById(R.id.tv_one);
        tvTitleScore = (TextView) findViewById(R.id.tv_title_score);
        tvTraderTitle = (TextView) findViewById(R.id.tv_trader_title);
        tvTraderAddress = (TextView) findViewById(R.id.tv_trader_address);
        tvTraderIntroDetail = (TextView) findViewById(R.id.tv_trader_intro_detail);
        ivTraderPic = (ImageView) findViewById(R.id.iv_trader_pic);
        ivTraderType = (ImageView) findViewById(R.id.iv_trader_type);
        ivTraderShare = (ImageView) findViewById(R.id.iv_trader_share);
        wwPhoto = (WebWin) findViewById(R.id.wwPhoto);
        ivPreferential = (ImageView) findViewById(R.id.iv_trader_hui);
        llMap = (LinearLayout) findViewById(R.id.ll_trader_ditu);
        tvTitleScore.setText(UserSp.getPoint());
        ivCall = (ImageView) findViewById(R.id.iv_trader_phone);
        llScore = (LinearLayout) findViewById(R.id.ll_score);
    }

    /**
     * 赋值和添加监听器
     */
    @SuppressWarnings("unchecked")
    private void findView() {
        tvTraderDetailTitle.setText(getResources().getString(
                R.string.shop_title));
        llScore.setVisibility(View.INVISIBLE);
        Intent intent = getIntent();
        if (intent.getStringExtra("HotTrader") != null
                && (!"".equals(intent.getStringExtra("HotTrader")))) {
            str = intent.getStringExtra("HotTrader");
        }
        map = (Map<String, Object>) intent.getSerializableExtra("detail");
        getDataFromServer();
        getShopDetail();
        ivCall.setOnClickListener(listener);
        ivTraderShare.setOnClickListener(listener);
        ivPreferential.setOnClickListener(listener);
        llMap.setOnClickListener(listener);
        llScore.setOnClickListener(listener);
    }

    /**
     * 下拉刷新的进度条
     */
    private void getDataFromServer() {
        dialog = DialogHelper.getInstance().createLoadingDialog(this, Constant.LOADING);
        dialog.show();
    }

    /**
     * 设置详情
     */

    private void setDetail() {
        /* 填照片 */

        uMtitle = mapDetail.get("merchantName").toString();/* 店铺名称 */
        uMcontent = mapDetail.get("introduction").toString();/* 店铺名称 */
        image = ImageDownloader.getImageDownloader();
        image.download(mapDetail.get("merchantLogo").toString(), ivTraderPic,
                ImageSize.IMAGE_SIZE_EXTRA_SMALL_RECTANGLE_JPG);
        tvTraderTitle.setText(uMtitle);
        merId = mapDetail.get("merID").toString();
        isHui();
        String category = mapDetail.get("category").toString();
        /* 判断是哪一个类型（外卖送餐，居家服务，生活杂货） */
        if (category.equals("1")) {
            ivTraderType.setBackgroundResource(R.drawable.waimaisongcan);
        } else if (category.equals("2")) {
            ivTraderType.setBackgroundResource(R.drawable.shenghuozahuo);
        } else if (category.equals("3")) {
            ivTraderType.setBackgroundResource(R.drawable.jujiafuwu);
        }
        tvTraderAddress.setText(mapDetail.get("stree").toString());
        tvTraderIntroDetail.setText(uMcontent);
        latitude = Float.parseFloat(mapDetail.get("latitude").toString());
        longitude = Float.parseFloat(mapDetail.get("longitude").toString());
        setWebView();
    }

    /**
     * 判断是否优惠，是否显示惠
     */
    private void isHui() {
        String isHui = mapDetail.get("activity").toString();
        if (!"1".equals(isHui)) {
            ivPreferential.setVisibility(View.GONE);
        }
    }

    /**
     * 设置照片的webview
     */
    private void setWebView() {
        String pics = mapDetail.get("merchantImgs").toString();
        wwPhoto.loadDataWithBaseURL(pics);
    }

    /**
     * 设置监听器
     */
    private OnClickListener listener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                /** 打电话 */
                case R.id.iv_trader_phone:
                    if (mapDetail == null) {
                        break;
                    }
                    String phone = mapDetail.get("phone").toString();
                    String name = mapDetail.get("merchantName").toString();
                    String time = TimeUtil.timeStampToDate(String.valueOf(System
                            .currentTimeMillis()));
                    String url = mapDetail.get("merchantLogo").toString();
                    Map<String, String> map = new LinkedHashMap<String, String>();
                    map.put("name", name);
                    map.put("phone", phone);
                    map.put("time", time);
                    saveFile(map);
                    PhoneCallUtil.getInstances().PhoneCall(TraderDetailActivity.this, phone);
                    break;
                /** 分享按钮 */
                case R.id.iv_trader_share:
                    shareBiz.share(uMtitle, uMcontent, Constant.SHOP_URL, merId);
                    break;
                /** 优惠 */
                case R.id.iv_trader_hui:
                    if (!NetworkUtil.isConnectedNet(TraderDetailActivity.this)) {
                        Toast.makeText(
                                TraderDetailActivity.this,
                                TraderDetailActivity.this.getResources().getString(
                                        R.string.net_disconnected),
                                Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (mapDetail == null) {
                        break;
                    }
                    Intent intent = new Intent();
                    intent.setClass(TraderDetailActivity.this, DetailActivity.class);
                    intent.putExtra("actvtID", mapDetail.get("activityID")
                            .toString());
                    startActivity(intent);
                    break;
                case R.id.ll_trader_ditu:
                    CommonJumper.jumpToBaiduLocation(TraderDetailActivity.this, longitude, latitude);
                    break;
                case R.id.ll_score:
                    if (!NetworkUtil.isConnectedNet(TraderDetailActivity.this)) {
                        Toast.makeText(
                                TraderDetailActivity.this,
                                TraderDetailActivity.this.getResources().getString(
                                        R.string.net_disconnected),
                                Toast.LENGTH_SHORT).show();
                        return;
                    }

                    intent = new Intent();
                    intent.setClass(TraderDetailActivity.this,
                            MyPointActivity.class);
                    startActivity(intent);


                    break;

                default:
                    break;
            }
        }
    };

    /**
     * 处理返回的信息数据
     */
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 6:
                    DialogHelper.closeDialog(dialog);
                    mapDetail = new HashMap<String, Object>();
                    mapDetail = (Map<String, Object>) JSONHelper.jsonToMap(
                            msg.obj.toString()).get("entity");
                    setDetail();
                    break;
                case 500:
                    DialogHelper.closeDialog(dialog);
                    ToastHelper.getInstance()._toast(
                            msg.obj.toString());
                    break;
                case 1011:
                    isLogin(dialog);
                    break;
                default:
                    break;
            }
        }

    };

    /**
     * 获得商家详情
     */
    private void getShopDetail() {
        Map<String, Object> mapSubmit = new HashMap<String, Object>();
        String merID = null;
        if (str != null) {
//			merID = map.get("linkID").toString();
            merID = map.get("merID").toString();
        } else {
            if (map == null) {
                Intent intent = getIntent();
                merID = intent.getStringExtra("merID");
                if (StringUtil.isBlank(merID)) {
                    merID = intent.getStringExtra("id");
                }
            } else {
                merID = map.get("merID").toString();
            }
        }
        mapSubmit.put("{merID}", merID);
        Map<String, Object> rootMap = new HashMap<String, Object>();
        rootMap.put("map", mapSubmit);
        rootMap.put("url", Constant.URL_MERCHANT_DETAIL);
        rootMap.put("wat", 6);
        new JSONRequest(JSONRequest.GET, rootMap, handler, HttpUtil.ACTION_URI);
    }

    /**
     * 储存通话记录
     *
     * @param map
     */
    @SuppressWarnings({"static-access", "rawtypes"})
    private void saveFile(Map map) {
        filename = UserSp.getRegPhone();
        FileHelper file = new FileHelper(this, filename + ".txt");
        file.saveFile(map, this.MODE_APPEND);
        hadCall = true;
    }

}
